package cn.zh.service.impl;

import cn.hutool.crypto.digest.MD5;
import cn.zh.commons.ResponseResult;
import cn.zh.entity.User;
import cn.zh.form.LoginForm;
import cn.zh.mapper.UserMapper;
import cn.zh.service.UserService;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author : 张航
 * @date : 2024-05-30 15:19
 * @description:
 **/
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    public ResponseResult userPage(Integer page, Integer limit, String username) {

        PageHelper.startPage(page,limit);
        List<User> users = userMapper.searchUsers(username);
        PageInfo<User> userPageInfo = new PageInfo<User>(users);
        long total = userPageInfo.getTotal();

        return ResponseResult.success().data(users).count(total);
    }

    public ResponseResult addUser(User user) {

        //初始用户密码：123456
        String defaultPassword = "123456";
        String MD5Password = MD5.create().digestHex16(defaultPassword);
        user.setPassword(MD5Password);

        //根据用户名查询用户是否存在
        User user1 = userMapper.selectUserByUsername(user.getUsername());
        if (!ObjectUtils.isEmpty(user1)){
            return ResponseResult.fail().message("用户已存在");
        }

        userMapper.insertUser(user);
        return ResponseResult.success().message("新用户添加成功");
    }

    public ResponseResult getUserById(Integer id) {

        User user = userMapper.selectUserById(id);

        return ResponseResult.success().data(user);
    }

    public ResponseResult editUser(User user) {

        userMapper.updateUser(user);

        return ResponseResult.success().message("用户更新成功");
    }

    public ResponseResult deleteUser(Integer[] ids) {

        userMapper.deleteUser(ids);
        return ResponseResult.success().message("用户删除成功");
    }

    public ResponseResult resetPassword(Integer id) {

        String password = "111111";
        String MD5Password = MD5.create().digestHex16(password);
        userMapper.updatePassword(id,MD5Password);

        return ResponseResult.success().message("密码重置成功");
    }

    public ResponseResult registerUser(User user) {

        try{
            String MD5Password = MD5.create().digestHex16(user.getPassword());
            user.setPassword(MD5Password);
            userMapper.insertUser(user);
        }catch (DuplicateKeyException e){
            e.printStackTrace();
            return ResponseResult.fail().message("用户名已存在");
        }
        return ResponseResult.success().message("用户注册成功");
    }

    public ResponseResult login(String username1,String password1,String captcha, HttpServletRequest request) {

        LoginForm loginForm = new LoginForm()
                .setUsername(username1)
                .setPassword(password1)
                .setCaptcha(captcha);

        //验证码
        String captcha1 = loginForm.getCaptcha();
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");

        if (!StringUtils.equals(captcha1,code)){
            return ResponseResult.fail().message("验证码错误");
        }

        //用户名
        User user = userMapper.selectUserByUsername(loginForm.getUsername());
        if (ObjectUtils.isEmpty(user)){
            return ResponseResult.fail().message("用户名或密码错误");
        }

        //密码
        String MD5Password = MD5.create().digestHex16(loginForm.getPassword());
        String DBPassword = user.getPassword();
        if (!StringUtils.equals(MD5Password,DBPassword)){
            return ResponseResult.fail().message("用户名或密码错误");
        }

        //将用户信息缓存在session中，用户后期非法请求拦截业务
        session.setAttribute("user",user);

        return ResponseResult.success().message("认证通过").data(user);
    }

    public ResponseResult getUserByUsername(String username) {
        User user = userMapper.selectUserByUsername(username);
        return ResponseResult.success().data(user);
    }

    public ResponseResult editPersonalPassword(String oldPassword, String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //1.判定当前密码是否正确
        String username = user.getUsername();
        String DBPassword = userMapper.selectUserByUsername(username).getPassword();
        System.out.println("DBPassword = " + DBPassword);
        String formPassword = MD5.create().digestHex16(oldPassword);
        System.out.println("formPassword = " + formPassword);
        if (!StringUtils.equals(DBPassword,formPassword)){
            return ResponseResult.fail().message("原始密码不正确");
        }
        //2.修改密码
        String newPassword = MD5.create().digestHex16(password);
        System.out.println("password = " + password);
        System.out.println("newPassword = " + newPassword);

        userMapper.editPersonalPassword(newPassword,user.getId());

        //清空session
        session.invalidate();

        return ResponseResult.success().message("密码修改成功");
    }

}
